const util = require('../../utils/util.js');
const user = require('../../services/user.js');
const Toast = require('../../utils/toast.js');
const app = getApp();
Page({
  data: {
    currentTab: '0',
    lesson_id: '',
    lessoninfo: {},
    lesson_commission:0,
    lesson_classinfo: 0,
    lesson_classlist: 0,
    class_type: 0, //课程类型 0 单独 1 系列 2 专栏
    lessontype:0, // 1是视频 2是语音
    isbuy: 0, //课程是否已经购买
    iscollect: 0, //是否已经收藏
    classnum: 0, //购买默认选项栏
    show: false,
    showCollection: false,//不再收藏
    unFollowshow: false,//取消关注弹窗
    unCollectionshow: false,//不再收藏
    sharepopshow: false,//分享弹窗
    showCanvas: false, // 显示canvas弹窗
    buyShow: false, //购买弹窗
    width: 0,
    height: 0,
    screenWidth: 0,
    screenHeight: 0,
    pixelRatio: 0,
    prurl: '',
    isIpx: app.globalData.isIpx //判断是否为iPhone X 默认为值false，iPhone X 值为true
  },
  //***页面加载 */
  onLoad: function(e) {
    //console.log(e.userid);
    app.globalData.topuserid = e.userid;//存储推荐人id

    let that = this;
    this.setData({ //保存课程的id数据
      lesson_id: e.id
    })
    this.getlessoninfo(e.id); //获取课程信息
    wx.getSystemInfo({ //保存页面信息
      success: function(res) {
        that.setData({
          width: res.windowWidth,
          height: res.windowHeight,
          screenWidth: res.screenWidth,
          screenHeight: res.screenHeight,
          pixelRatio: res.pixelRatio,
        })
      }
    })
  },
  //***页面显示 */
  onShow: function() {
    this.getlessonstatus()
  },
  //***获取课程信息接口 */
  getlessoninfo: function(lesson_id) {
    let that = this;
    util.request('school/getlessoninfo', {
      lesson_id: lesson_id
    }, 'GET').then(function(res) {
      console.log(res.data);
      let lesson_commission = (res.data.lessoninfo.lesson_price * res.data.lessoninfo.lesson_commission_per / 10000).toFixed(2) ;
      if (res.errno === 0) {
        that.setData({
          lessoninfo: res.data.lessoninfo,
          lesson_classinfo: res.data.lesson_classinfo,
          lesson_classlist: res.data.lesson_classlist,
          lesson_commission: lesson_commission,
        })
        if (res.data.lesson_classinfo != 0) {
          that.setData({
            class_type: res.data.lesson_classinfo.class_type,
            //classnum: res.data.lesson_classinfo.class_type,
          })
          if (res.data.lesson_classinfo.class_type == 2) {
            that.setData({
              //class_type: res.data.lesson_classinfo.class_type,
              classnum: res.data.lesson_classinfo.class_type,
            })
          }

        }

      } else {
        console.log(2222)
      }
    });
  },
  //***获取课程的关注和购买状态 */
  getlessonstatus: function() {
    let that = this;
    util.request('school/getlessonstatus', {
      lesson_id: that.data.lesson_id,
      lesson_type: 1,
    }, 'GET').then(function(res) {
      console.log(res.data);
      if (res.errno === 0) {
        that.setData({
          isbuy: res.data.isbuy,
          iscollect: res.data.iscollect,
          lessontype: res.data.lessontype
        })
      }
    });
  },
  buy: function() {
    let that = this;
    user.checkLogin().then((res) => {
      //console.log(res)
      if (res == true) {
        console.log('已授权')
        //购买
        that.setData({
          buyShow: true
        })

      }

    }).catch((err) => {
      console.log('未授权')
    });
  },
  swichNav: function(e) {
    let tabid = e.currentTarget.dataset.tabid;
    //console.log(e);
    this.setData({
      currentTab: tabid,
    });
  },
  // share:function(e){
  //   wx.navigateTo({
  //     url: '/pages/share/share?lesson_id=' + e.currentTarget.dataset.lessonid,
  //   })
  // },
  shareInfo: function() {
    let flag = true;
    user.checkLogin().then((res) => {
      if (res == true) {
        console.log('已授权')
      }
    }).catch((err) => {
      console.log('未授权')
      flag = false;
    });
    if (flag) {
      this.setData({
        sharepopshow: true
      })
      this.getCanvas()
    }
  },
  onShareAppMessage: function(res) {
    let that = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: that.data.lessoninfo.lesson_name,
      path: '/pages/lessoninfo/lessoninfo?id=' + that.data.lesson_id,
      imageUrl: that.data.lessoninfo.lesson_img || 'http://p8pho5rm4.bkt.clouddn.com/sharelogo_new.png'
    }
    that.setData({
      sharepopshow: false
    })
  },
  closeShare: function(res) {
    this.setData({
      sharepopshow: false
    })
  },
  createCanvas: function() {
    this.setData({
      showCanvas: true,
      sharepopshow: false
    })
  },
  closeCanvas: function() {
    this.setData({
      showCanvas: false
    })
  },
  //当有banner图的时候
  getCanvas() {
    let that = this
    console.log(that.data.lessoninfo)
    // let promise1 = new Promise(function (resolve, reject) {
    //   wx.getImageInfo({
    //     src: 'http://p8pho5rm4.bkt.clouddn.com/shareimg1.png',
    //     success: function (res) {
    //       resolve(res)
    //     }
    //   })
    // });
    // //获取banner的框
    // let promise2 = new Promise(function (resolve, reject) {
    //   wx.getImageInfo({
    //     src: 'http://p8pho5rm4.bkt.clouddn.com/share.png',
    //     success: function (res) {
    //       resolve(res);
    //     }
    //   })
    // });
    //获取banner图
    let promise3 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: that.data.lessoninfo.lesson_img,
        success: function(res) {
          resolve(res);
        }
      })
    });
    //分享二维码
    let promise4 = new Promise(function(resolve, reject) {
      if (wx.getStorageSync('erweima') && that.data.lesson_id == wx.getStorageSync('lessonid')) {
        wx.getImageInfo({
          src: wx.getStorageSync('erweima'),
          success: function(res) {
            resolve(res);
          }
        })
      } else {
        util.request('wxqcode/getqrcode', {
          lesson_id: that.data.lesson_id,
          code_type: 'wxcode'
        }, 'POST').then(function(res) {
          console.log(res)
          if (res.errno === 0) {
            wx.setStorageSync('erweima', res.data)
            wx.setStorageSync('lessonid', that.data.lessonid)
            wx.getImageInfo({
              src: res.data,
              success: function(res) {
                resolve(res);
              }
            })
          }
        });
      }
    });
    Promise.all([
      promise3, promise4
    ]).then(res => {
      const ctx = wx.createCanvasContext('shareImg')
      //获取背景图
      ctx.setFillStyle('#fff')
      ctx.fillRect(0, 0, 280, 340)
      //ctx.drawImage(res[0].path, 0, 0, 280, 320)
      //获取背景框
      //ctx.drawImage(res[1].path, 11, 32, 260, 150)
      //获取banner
      ctx.drawImage(res[0].path, 10, 26, 260, 180);
      //二维码
      ctx.drawImage(res[1].path, 6, 250, 76, 76);
      ctx.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
      ctx.fillStyle = "#000";
      ctx.setFontSize(14)
      ctx.font = '14px sans-serif';
      ctx.fillText('如果你还无法简洁！', 11, 230);
      ctx.fillStyle = "#2b97f8";
      ctx.font = '12px sans-serif';
      ctx.fillText(`@${wx.getStorageSync('userInfo').nickname}`, 92, 270);
      ctx.fillStyle = "#000";
      ctx.fillText("推荐了一堂好课", 92, 290);
      ctx.fillText("长按识别小程序码查看课程", 92, 310);
      ctx.draw()
    })
  },
  //canvas转化为图片并预览
  /**
   * 生成分享图
   */
  share: function() {
    var that = this
    wx.showLoading({
      title: '努力生成中...'
    })
    wx.canvasToTempFilePath({
      width: 280,
      height: 340,
      destWidth: 280 * that.data.pixelRatio,
      destHeight: 340 * that.data.pixelRatio,
      canvasId: 'shareImg',
      fileType: 'png',
      success: function(res) {
        that.setData({
          prurl: res.tempFilePath
        })
        wx.hideLoading()
        that.save()
      },
      fail: function(res) {
        console.log(res)
      }
    })
  },

  /**
   * 保存到相册
   */
  save: function() {
    var that = this
    //生产环境时记得这里要加入获取相册授权的代码
    wx.saveImageToPhotosAlbum({
      filePath: that.data.prurl,
      success(res) {
        wx.showModal({
          content: '图片已保存到系统相册~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#2b97f8',
          success: function(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              that.setData({
                showCanvas: false
              })
            }
          }
        })
      }
    })
  },
  collection: function() {
    let that = this;
    //添加或是取消收藏
    util.request('collect/getcollect', {
        lesson_id: that.data.lesson_id,
        lesson_type: that.data.lessontype
      }, "POST")
      .then(function(res) {
        let _res = res;
        if (_res.errno == 0) {
          if (_res.data.type == 'add') {
            Toast('收藏成功!', 'success')
            that.setData({
              iscollect: 1
            });
          } else {
            Toast('取消收藏!', 'success')
            that.setData({
              iscollect: 0
            });
          }

        } else {

        }
      });
  },
  //***选择购买的类型 0 单独购买  1 系列购买 2 专栏购买 */
  chooseClass(e) {
    this.setData({
      classnum: e.currentTarget.dataset.classnum
    })
  },
  closeBuy() {
    this.setData({
      buyShow: false
    })
  },
  closeCollection() {
    this.setData({
      unCollectionshow: false
    })
  },
  consultation() {
    this.setData({
      consultShow: true
    })
  },
  closeConsult() {
    this.setData({
      consultShow: false
    })
  },
  sendConsult() {
    this.setData({
      consultShow: false
    })
  },
  pay: function() {
    this.postorder();
  },
  postorder: function() {
    //console.log(this.data.classnum)
    var that = this;
    var topuserid = app.globalData.topuserid;
    if (this.data.classnum == 0) { //如果是单独购买课程
      let commission = this.data.lesson_commission;
      var orderinfo = {
        lesson_type: 1,
        lesson_id: this.data.lessoninfo.lesson_id,
        class_id: 0,
        lesson_amount: this.data.lessoninfo.lesson_price,
        lesson_name: this.data.lessoninfo.lesson_name,
        commission: commission * 100,
        topuserid: topuserid
      }
    }
    if (this.data.classnum == 1 || this.data.classnum == 2) {
      let commission = (this.data.lesson_classinfo.class_price * this.data.lesson_classinfo.class_commission_per / 10000).toFixed(2);
      var orderinfo = {
        lesson_type: 1,
        lesson_id: 0,
        class_type: that.data.classnum,
        class_id: this.data.lesson_classinfo.id,
        lesson_amount: this.data.lesson_classinfo.class_price,
        lesson_name: this.data.lesson_classinfo.class_name,
        commission: commission * 100,
        topuserid: topuserid
      }
    }


    var that = this;
    console.log(orderinfo);
    util.request('order/postaddlessonorder', {
      orderinfo: orderinfo
    }, 'POST').then(function(res) {
      console.log(res.data);
      if (res.errno === 0) {
        that.getpayinfo(res.data.order_id)
      }
    });

  },
  getpayinfo: function(order_id) {
    var that = this;
    util.request('pay/lessonorderpay', {
      order_id: order_id
    }, 'POST').then(function(res) {
      console.log(res.data);
      if (res.errno === 0) {
        that.paynow(res.data.wxpayinfo);
      }
    });

  },
  paynow: function(obj) {
    let that = this;
    console.log(obj)
    var as = obj.nonce_str;
    console.log(as);
    console.log(typeof as);
    wx.requestPayment({
      'timeStamp': obj.timeStamp + '',
      'nonceStr': obj.nonceStr,
      'package': obj.package,
      'signType': 'MD5',
      'paySign': obj.paySign,
      'success': function(res) {
        Toast('支付成功!', 'success');
        that.getlessonstatus()
      },
      'fail': function(res) {
        Toast('支付失败!');
        return;
      }
    })
  },
  golessonstudy: function(e) {
    let that = this
    //console.log(e.currentTarget.dataset.id);
    let id = e.currentTarget.dataset.id;
    console.log(id);
    wx.navigateTo({
      url: `/pages/video/video?id=${id}&title=${that.data.lessoninfo.lesson_name}`
    })
  },
  toCataloglesson: function(e) {
    let lesson_id = e.currentTarget.dataset.lessonid;
    wx.navigateTo({
      url: '/pages/lessoninfo/lessoninfo?id=' + lesson_id,
    })
  }

})